package com.labot.webapp.filter;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices;

import com.labot.model.User;
import com.labot.util.DateUtil;


public class InvalidateFilter implements Filter {
	
	//Map username and date
	private static Map<String, Date> usersToInvalidate = new HashMap<String, Date>();
	
	public static void addUserToInvalidate(String userName) {
		usersToInvalidate.put(userName.toLowerCase(), new Date());
	}
	
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain)
    throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        Integer sessionTimeout = request.getSession().getMaxInactiveInterval();

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) { //If not Anonymous
        	//user is authenticated!
        	try {        		
        		User user = (User)authentication.getPrincipal();
        		if (user != null) {
        			//check if needs to be invalidated
        			Date invalidateRequestDate = usersToInvalidate.get(user.getUsername());
        			if (invalidateRequestDate != null) {
        				Integer seconds = DateUtil.diffSecondsBetweenDates(invalidateRequestDate, new Date());
        				usersToInvalidate.remove(user.getUsername().toLowerCase()); //Take out from the list!
        				if (seconds <= sessionTimeout) {
        					HttpServletResponse httpResponse = (HttpServletResponse) res;
        					authentication.setAuthenticated(false);
        					chain.doFilter(req, res);
        					request.getSession(false).setAttribute("invalidate", "true");
        					httpResponse.sendRedirect(request.getContextPath() + "/logout?invalidate=true");
        					return;
        				}
        			}
        		}
        	} catch (Exception e) {
        		//anonimo?
        	}
        }

        //Filter Ends
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }

		
}
